/*
 * Name: Joon Ho Cho
 * Date: 10/24/2008
 * Course: 15-437
 */
package scheduler.controller;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.mybeans.dao.DAOException;
import scheduler.databean.Schedule;
import scheduler.databean.User;
import scheduler.formbean.LoginForm;

import scheduler.model.Model;
import scheduler.model.ScheduleDao;
import scheduler.model.UserDao;


public class CreateNewScheduleAction extends Action {
		
	private ScheduleDao scheduleDao;
	private UserDao userDao;


    public CreateNewScheduleAction(Model model) {
		scheduleDao= model.getScheduleDao();
	
		userDao=model.getUserDao();
		
	}

    public String getName() { return "create.do"; }

    public String perform(HttpServletRequest request) {
        try {
	        HttpSession session = request.getSession(true); 
	        User user = (User) session.getAttribute("user");
	      
	        if (user == null) {
				LoginForm form = new LoginForm();
				form.setRedirect("/add-bookmark.do");
		        request.setAttribute("form",form);
				return "login.jsp";
			}
	        Schedule[] schedule=scheduleDao.getSchedule(user.getUserName(), user.getNumSchedule()-1);
	        System.out.println("num"+user.getNumSchedule());
	        System.out.println(schedule.length);
	        if(schedule.length!=0 ||user.getNumSchedule()==0){	        	
	        	user=userDao.makeNew(user.getUserName(), user.getNumSchedule());  
	        	request.getSession().setAttribute("user", user);	        
	        }
	              
	        request.getSession().setAttribute("scheduleID", user.getNumSchedule()-1);
			
			return "schedule.do";
        } catch (DAOException e) {
        	e.printStackTrace();
        	request.setAttribute("dbError",e.getMessage());
        	return "db-error.jsp";
		}
    }
}
